package cn.t.facade.user;


import cn.t.converter.user.RoleFirmDTOConverter;
import cn.t.core.exception.BizException;
import cn.t.core.facade.FacadeImpl;
import cn.t.core.mode.YesNoEnum;
import cn.t.dto.user.RoleFirmDTO;
import cn.t.core.enums.base.BaseStatusEnum;
import cn.t.core.enums.base.CommonError;
import cn.t.model.user.RoleFirmDO;
import cn.t.service.user.CustomerFirmService;
import cn.t.service.user.ParticipantInfoService;
import cn.t.service.user.ParticipantRoleService;
import cn.t.service.user.RoleFirmService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 部门信息表服务编排
 *
 * @author l
 */
@Slf4j
@Service
@AllArgsConstructor
public class RoleFirmFacade extends FacadeImpl<RoleFirmDTO, RoleFirmDO, RoleFirmDTOConverter, RoleFirmService> {


    @Override
    public boolean add(RoleFirmDTO dto) {
        hasDuplicateFirm(dto);
        return service.add(converter.dto2Model(dto));
    }

    public boolean update(Long roleId, List<Long> firmIds) {
        if(CollectionUtils.isEmpty(firmIds)){
            service.removeByRoleId(roleId);
            return true;
        }

        for (Long firmId : firmIds) {
            customerFirmService.isExistedFirm(firmId);
        }


        RoleFirmDO template = new RoleFirmDO();
        template.setRoleId(roleId);
        template.setIsDeleted(YesNoEnum.FALSE);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        List<RoleFirmDO> existsRoleFirm = service.findByModel(template, 0, 10000, null, null);




       // 收集删除的公司id
        ArrayList<Long> firms = new ArrayList<>();
        Set<Long> existsFirmIds = Collections.emptySet();
        if (!CollectionUtils.isEmpty(existsRoleFirm)) {
            existsFirmIds = existsRoleFirm.stream().map(RoleFirmDO::getFirmId).collect(Collectors.toSet());
            for (RoleFirmDO existsData : existsRoleFirm) {
                // 如果最新提交的企业 ID 清单里，已经没有历史清单数据时。
                if (firmIds != null && !firmIds.contains(existsData.getFirmId())) {
                    service.removeById(existsData.getId());
                    //删除角色和参与者信息关联
                    customerFirmService.removeById(existsData.getId());
                    firms.add(existsData.getFirmId());
                }
            }
        }
        //删除角色和参与者信息关联
        if (!CollectionUtils.isEmpty(firms)){
            firms.forEach(firmId -> {
                    participantRoleService.deleteParticipantRoleByRoleId(roleId, firmId);
            });
        }
        // 新增
        if (!CollectionUtils.isEmpty(firmIds)) {
            for (Long firmId : firmIds) {
                if (existsFirmIds.contains(firmId)) {
                    continue;
                }
                RoleFirmDTO newData = new RoleFirmDTO();
                newData.setRoleId(roleId);
                newData.setFirmId(firmId);
                add(newData);
            }
        }

        return true;
    }

    public void hasDuplicateFirm(RoleFirmDTO dto) {

        RoleFirmDO template = new RoleFirmDO();
        template.setRoleId(dto.getRoleId());
        template.setFirmId(dto.getFirmId());

        List<RoleFirmDO> tmp = service.findByModel(template, 0, 100, null, null);
        if (tmp != null && !tmp.isEmpty()) {
            log.warn("当前角色已绑定此公司：{} - {}", dto.getRoleId(), dto.getFirmId());
            throw new BizException(CommonError.BIZ_EXCEPTION, "当前角色已绑定此公司");
        }
    }

    @Autowired
    private CustomerFirmService customerFirmService;
    @Resource
    private ParticipantRoleService participantRoleService;
    @Resource
    private ParticipantInfoService participantInfoService;


}





